package com.sun.springbootfiledownload.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @version 1.0
 * @Package: com.sun.springbootfiledownload.controller
 * @ClassName: FileController
 * @Author: sgq
 * @Date: 2025/4/9 9:34
 * @Description: TODD
 */
@Slf4j
@RestController
@RequestMapping("/api/file")
public class FileController {

    // 上传文件存储目录
    private static final String UPLOAD_DIR = "uploads/";

    /**
     * 文件上传接口
     *
     * @param file 上传的文件
     * @return 上传结果消息
     */
    @PostMapping("/upload")
    public String uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            // 检查上传目录是否存在，不存在则创建
            File uploadDir = new File(UPLOAD_DIR);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }

            // 获取文件原始名称
            String originalFilename = file.getOriginalFilename();
            // 构建文件保存路径
            Path filePath = Paths.get(UPLOAD_DIR, originalFilename);

            // 保存文件到本地
            file.transferTo(filePath);
            log.info("文件上传成功: {}", originalFilename);
            return "文件上传成功: " + originalFilename;
        } catch (IOException e) {
            log.error("文件上传失败", e);
            return "文件上传失败: " + e.getMessage();
        }
    }

    /**
     * 文件下载接口
     *
     * @param filename 要下载的文件名
     * @return 文件响应实体
     */
    @GetMapping("/download/{filename}")
    public ResponseEntity<byte[]> downloadFile(@PathVariable String filename) {
        try {
            // 构建文件路径
            Path filePath = Paths.get(UPLOAD_DIR, filename);
            // 读取文件内容为字节数组
            byte[] fileContent = Files.readAllBytes(filePath);

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", filename);

            log.info("文件下载成功: {}", filename);
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(fileContent);
        } catch (IOException e) {
            log.error("文件下载失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }
}
